<template>
    <a-layout class="worksheetAPI">
      <a-layout-sider class="aside">
        <a-menu
          mode="inline"
          :open-keys="openKeys"
          style="width: 200px;"
          @openChange="onOpenChange"
          @click="onClick"
          :selectedKeys="selectedKeys"
        >
          <a-menu-item key="authorization">
            <span style="font-weight: bold">授权管理</span>
          </a-menu-item>
          <a-menu-item key="applicationMess">
            <span style="font-weight: bold">获取应用信息</span>
          </a-menu-item>
          <a-sub-menu>
            <span slot="title"><span style="font-weight: bold">工作表</span></span>
            <!-- <a-menu-item key="worksheetStruct">获取工作表结构信息</a-menu-item> -->
            <a-sub-menu :key="ws.id" v-for="ws in worksheetList">
              <span slot="title"><span style="font-weight: bold">{{ ws.name }}</span></span>
              <a-menu-item :key="'FieldMap'+ws.id">字段对照表</a-menu-item>
              <a-menu-item v-for="api in apiData" :key="api.key+ws.id">
                {{ api.title }}
              </a-menu-item>
            </a-sub-menu>
          </a-sub-menu>
          
        </a-menu>
      </a-layout-sider>
      <a-layout-content class="auth-content" @scroll="handleScroll">
        <div id="authorization">
          <h1 class="title">授权管理</h1>
          <a-table :columns="authColumns" :data-source="authData" size="middle" :pagination="false" rowKey="ID">
            <span slot="authType" slot-scope="authType">
              {{ authType === '0' ? '未启用' : authType === '1' ? '只读' : '全部' }}
            </span>
            <span slot="action" slot-scope="text, record">
              <a-dropdown>
                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                   <a-icon type="more" />
                </a>
                <a-menu slot="overlay">
                  <a-menu-item key="0" v-if="record.AuthType !== '2'">
                    <a @click="handleEditSecret(record, '2')">授权全部</a>
                  </a-menu-item>
                  <a-menu-item key="1" v-if="record.AuthType !== '1'">
                    <a @click="handleEditSecret(record, '1')">授权只读</a>
                  </a-menu-item>
                  <a-menu-item key="2" v-if="record.AuthType !== '0'">
                    <a @click="handleEditSecret(record, '0')">取消授权</a>
                  </a-menu-item>
                  <a-menu-divider/>
                  <a-menu-item key="3">
                     <a style="color: red" @click="handleDeleteSecret(record.ID)">删除</a>
                  </a-menu-item>
                </a-menu>
            </a-dropdown>
            </span>

            <div slot="expandedRowRender" slot-scope="record">
              <Urls
                name="URL"
                :urls="getWhiteListData(record)"
                @addUrl="urls => updateWhiteList(record, urls)"
                @deleteUrl="urls => updateWhiteList(record, urls)"
              />
            </div>

          </a-table>
          <a class="addSecret" @click="handleAddSecret"><a-icon type="plus" /> Add Secret</a>
        </div>
        <div id="applicationMess">
          <h1 class="title">获取应用信息</h1>
          <api-info
            :id="applicationData.key"
            :method="applicationData.method"
            :title="applicationData.title"
            :url="applicationData.url"
            :fields="applicationData.fields"
            :key="applicationData.key"
          />
        </div>
        <div v-for="ws in worksheetList" :key="ws.id">
          <div style="margin: 50px 0" :id="'FieldMap'+ws.id">
            <h1 class="title">{{ ws.name }}</h1>
            <h2 class="title">字段对照表</h2>
            <a-table :columns="columns" :data-source="data[ws.id]" size="middle" :pagination="false">

            </a-table>
          </div>
          <api-info
            :id="item.key+ws.id"
            :method="item.method"
            :title="item.title"
            :url="item.url"
            :fields="item.fields"
            v-for="item in apiParams[ws.id]"
            :key="item.key"
          />
        </div>
      </a-layout-content>
    </a-layout>
</template>

<script>
import ApiInfo from './components/ApiInfo'
import { DataType } from './DataType'
import { addSecret, deleteSecret, editSecret, getApiData, getSecret, getWorksheetDetail, getWorksheetList } from '@/api/worksheet'
import Urls from './components/Urls'
import qs from 'qs'

const columns = [
  {
    title: '字段ID',
    dataIndex: 'fieldId',
    key: 'fieldId',
  },
  {
    title: '字段名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '说明',
    key: 'desc',
    dataIndex: 'desc',
  }
];

const authColumns = [
  {
    dataIndex: 'AppKey',
    key: 'AppKey',
    title: 'AppKey',
    width: '110px'
  },
  {
    title: 'SecretKey',
    dataIndex: 'AppSecret',
    key: 'AppSecret',
    width: '150px'
  },
  {
    title: 'Sign',
    dataIndex: 'Sign',
    key: 'Sign',
    width: '300px',
  },
  {
    title: '授权类型',
    key: 'AuthType',
    dataIndex: 'AuthType',
    width: '60px',
    scopedSlots: { customRender: 'authType' }
  },
  {
    title: '备注',
    key: 'Remark',
    dataIndex: 'Remark',
    width: '60px'
  },
  {
    title: 'Action',
    key: 'action',
    width: '60px',
    scopedSlots: { customRender: 'action' },
  },
];

const whiteListColumns = [
  {
    dataIndex: 'WhiteList',
    key: 'WhiteList',
    title: 'WhiteList',
    // width: '110px'
    scopedSlots: { customRender: "whiteList" }
  }
]

export default {
  name: 'WorksheetApi',
  components: { Urls, ApiInfo },
  created () {
    let _this = this
    this.apiData = []
    this.appId = this.$route.params.id;
    // 查询授权
    this.getSecretList()
    getApiData().then(res => {
      if (res.status === 200) {
        res.data.data.forEach(item => {
          if(item.key === 'getApp'){
            this.applicationMess = item;
          // } else if(item.key === 'getWorksheetInfo') {
          //   this.worksheetStruct = item
          } else {
            this.apiData.push(item)
          }
        })
        // this.apiData = res.data.data
      }
    })

    getWorksheetList({appId: this.appId}).then(res => {
      _this.worksheetList = res.data.data
      _this.initData()
      // _this.worksheetList.forEach(ws => {
      //   _this.initData(ws.id)
      // })
    })
  },
  mounted(){
  },
  data () {
    return {
      apiData: [],
      authData: [],
      whiteListData: [
        {
          WhiteList: 'WhiteList',
        }
      ],
      appId: '',
      authColumns,
      columns,
      whiteListColumns,
      data: {},
      mdl: {},
      worksheetList: [],
      applicationMess: {},
      worksheetStruct: {},
      rootSubmenuKeys: ['sub1', 'sub2', 'sub4'],
      openKeys: ['sub2'],
      selectedKeys: ['authorization'],
      apis2: ['字段对照表', '获取列表', '新建行记录', '批量新建行记录', '获取行记录详情', '更新行记录详情', '删除行记录'],
      apis: [
        {
          key: 'FieldMap',
          value: '字段对照表',
        },
        {
          key: 'GetList',
          value: '获取列表',
        },
        {
          key: 'AddRow',
          value: '新建行记录',
        },
        {
          key: 'AddRows',
          value: '批量新建行记录',
        },
        {
          key: 'GetRow',
          value: '获取行记录详情',
        },
        {
          key: 'EditRow',
          value: '更新行记录详情',
        },
        {
          key: 'DeleteRow',
          value: '删除行记录',
        },
      ]
    };
  },
  // watch:{
  //   mdl(){
  //     this.setData()
  //   }
  // },
  methods: {
    updateWhiteList (record, urls) {
      const params = Object.assign({}, record, { WhiteList: urls })
      editSecret(params).then(res => {
          if (res.Code === 200) {
            this.$message.success('修改成功')
            const index = this.authData.findIndex(v => v.ID === params.ID)
            if (index > -1) {
              this.authData.splice(index, 1, params)
            }
          } else {
            this.$message.error('修改失败')
          }
        })
    },
    getWhiteListData (record) {
      if (!record || !Array.isArray(record.WhiteList)) {
        return []
      }
      return record.WhiteList
    },
    initData () {
      let mdl = {};
      this.worksheetList.forEach(item => {
        let id = item.id;
        mdl[id] = item
      })
      this.mdl = mdl
      this.setData()
      // getWorksheetDetail(id).then(res => {
      //     if (res.status === 200) {
      //       this.$set(this.mdl,id,res.data.data)
      //       // this.mdl[id] = res.data.data
      //       this.setData()
      //     }
      // })
    },
    setData () {
      // this.data = {}
      for(const id in this.mdl){
        this.data[id] = this.mdl[id].fields.map(field => {
          return {
            key: field.name,
            fieldId: field.name,
            name: field.alia,
            type: DataType.getName(field.dataType),
            desc: DataType.getDesc(field.dataType)
          }
        })
      }
    },
    getSecretList () {
      getSecret().then(res => {
        if (res.data.Code === 200) {
          this.authData = res.data.Data
        }
      })
    },
    handleScroll (e) {
      // console.log('scroll', e)
      const scrollTop = e.target.scrollTop
      const domData = []
      e.target.children.forEach(d => {
        domData.push({
          key: d.id,
          offsetTop: d.offsetTop
        })
      })
      for (let i = 0; i < domData.length - 1; i++) {
        if (scrollTop >= domData[i].offsetTop && scrollTop < domData[i + 1].offsetTop) {
            this.selectedKeys = [domData[i].key]
            break
        }
        if (i === domData.length - 2) {
          // console.log('lastOne', domData[i + 1].key)
          this.selectedKeys = [domData[i + 1].key]
        }
      }
    },
    handleAddSecret () {
      addSecret().then(res => {
        if (res.data.Code === 200) {
          this.$message.success('添加成功')
          this.getSecretList()
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    handleEditSecret (record, authType) {
      const params = Object.assign({}, record, { AuthType: authType })
      editSecret(params).then(res => {
        if (res.data.Code === 200) {
          this.$message.success('修改成功')
          this.getSecretList()
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    handleDeleteSecret (id) {
      if (id) {
        this.$confirm({
          content: "确认删除此密钥？",
          onOk: () => {
            deleteSecret(id).then(res => {
              if (res.data.Code === 200) {
                this.$message.success('删除成功')
                this.getSecretList()
              } else {
                this.$message.error('删除失败')
              }
            })
          }
        })
      }
    },
    onOpenChange (openKeys) {
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1);
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys;
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },
    onClick ({ item, key, keyPath }) {
      // console.log(item, key, keyPath)
      this.selectedKeys = [key]
      const target = document.getElementById(key)
      target && target.scrollIntoView(true)
    },
    getFilterSecret () {
      const filterData = this.authData.reduce((pre, cur) => {
        if (!pre[cur.AuthType]) {
          pre[cur.AuthType] = []
        }
        pre[cur.AuthType].push(cur)
        return pre
      }, {})
      for (let i = 2; i >= 0; i--) {
        if (filterData[i]) {
          return filterData[i][0]
        }
      }
      return {}
    },
    getFieldData () {
      let fieldData = {}
      for(const id in this.mdl){
        let mdlItem = this.mdl[id];
        if(mdlItem && mdlItem.fields){
          let data =  mdlItem.fields.reduce((pre, cur) => {
            pre[cur.name] = DataType.getExample(cur.dataType)
            return pre
          }, {})
          fieldData[id] = data
        }
      }
      return fieldData
    }
  },
  computed: {
    applicationData(){
      if(!this.applicationMess.fields) return {}
      const secret = this.getFilterSecret()
      this.applicationMess.fields.forEach(f => {
            switch (f.name) {
              case 'App-Key':
                f.value = secret.AppKey || ''
                break
              case 'Sign':
                f.value = secret.Sign || ''
                break
              case 'appId':
                f.value = this.appId
                break
            }
        })
        return this.applicationMess
    },
    apiParams : {
      get(){
        let result = {}
        const secret = this.getFilterSecret()
        const fieldData = this.getFieldData()
        for(let id in this.mdl){
          let mdlItem = this.mdl[id];
          let apiData = JSON.parse(JSON.stringify(this.apiData))
          result[id] = apiData.map(a => {
            a.fields.forEach(f => {
              switch (f.name) {
                case 'App-Key':
                  f.value = secret.AppKey || ''
                  break
                case 'Sign':
                  f.value = secret.Sign || ''
                  break
                case 'appId':
                  f.value = mdlItem.visualId || (mdlItem.visualData && mdlItem.visualData[1])
                  break
                case 'worksheetId':
                  f.value = id
                  break
                case 'data':
                  f.value = fieldData[id]
                  break
                case 'rows':
                  f.value = [fieldData[id]]
                  break
              }
            })
            
            return a
          })
        }
        return result
      },
      set(){}
    }
  }
}
</script>

<style scoped>

  .aside {
    min-height: 85vh;
    background: #fff;
    overflow: auto;
  }

  .aside .ant-menu, .ant-menu-submenu, .ant-menu-item {
    /*background-color: #fafafa;*/
  }

  .auth-content {
    margin-left: 20px;
    padding: 0 10px;
    /* max-height: 85vh; */
    overflow: auto;
  }
  .auth-content>.api-info:last-child {
    height: calc(85vh - 50px);
  }

  .auth-content::-webkit-scrollbar-thumb {
    visibility: hidden;
  }
  .auth-content:hover::-webkit-scrollbar-thumb {
    visibility: visible;
  }

  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  ::-webkit-scrollbar-button, ::-webkit-scrollbar-corner {
    display: none;
    width: 0;
    height: 0;
  }

  ::-webkit-scrollbar-thumb {
    width: 6px;
    height: 6px;
    border-radius: 6px;
    background: rgba(187, 187, 187, 0.8);
    background-clip: padding-box;
    border: 2px solid transparent;
  }

  .title{
    position: relative;
    line-height: 48px;
    font-size: 28px;
    font-weight: bold;
    color: #202d40;
    transition: color .3s ease-out;
  }
  h1.title {

  }
  h2.title {
    line-height: 36px;
    font-size: 16px;
  }
  h3.title {
    line-height: 20px;
    font-size: 11px;
    padding: 8px 0;
    color: #7d8899;
    border-bottom: 2px solid rgba(32,45,64,0.1);
  }

  ol, ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  a.addSecret {
    display: inline-block;
    margin-top: 20px;
  }
</style>

<style>
.worksheetAPI.ant-layout.ant-layout-has-sider{
  height: 100%;
}
</style>
